package main

import (
	"context"
	"recharge/logger"
	"strconv"
	"sync"
	"time"
)

type Order struct {
	ID          int
	EquidmentId string    `gorm:"column:equidment_id"`
	Electric    int64     `gorm:"column:electric"`
	State       int64     `gorm:"column:state"`
	CreatedAt   time.Time `gorm:"column:created_at"`
	UpdatedAt   time.Time `gorm:"column:updated_at"`
}

func (this *Order) TableName() string {
	return "order"
}

//自动结束订单
func CronEndOrder(wg *sync.WaitGroup, ctx context.Context) {
	//订单自动结束监听
	logger.Log.Info("订单自动结束监听")
	defer wg.Done()
	t := time.NewTicker(3 * time.Minute)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			logger.Log.Info("设备监听 停止")
			return
		case <-t.C:
			db := GetDB()
			//查询设备更新状态在3分钟前的
			var queryResult []*Order
			db.Table(new(Order).TableName()).Where("state=0").Find(&queryResult)
			for _, m := range queryResult {
				//
				logger.Log.Info(m.ID, m.EquidmentId, "目前已充值", time.Now().Unix()-m.CreatedAt.Unix(),
					"秒", "需要充电", m.Electric*3600, "秒")
				if time.Now().Unix()-m.CreatedAt.Unix() > m.Electric*3600 {
					en := &DeviceNumber{}
					db.Table(new(DeviceNumber).TableName()).Where("id=?", m.EquidmentId).First(en)
					if en.ID > 0 {
						n, _ := strconv.Atoi(en.Number)
						CallbackOrder(en.EID, int32(n))
						_ = GBEndRecharge(en.EID, n, 0, 0, 0)
					}
				}
			}
		}
	}
}
